package com.sheenhan.gdemo

import android.app.Activity
import android.app.Application
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import java.lang.Exception
import java.lang.reflect.Field

class LaunchActivity : AppCompatActivity() {
    private val TAG = "LaunchActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch)
        findViewById<Button>(R.id.btn_start).setOnClickListener {
            startActivity(Intent(this, MainActivity::class.java))
        }
        findViewById<Button>(R.id.btn_get).setOnClickListener {
            var data = getActivitiesByApplication(application)
            data?.forEach {
                Log.e(TAG, "act_name: " + it.toString())
            }
        }
    }


    private fun getActivitiesByApplication(application: Application): List<Activity?>? {
        var list: MutableList<Activity?>? = ArrayList()
        try {
            val applicationClass: Class<Application> = Application::class.java
            val mLoadedApkField: Field = applicationClass.getDeclaredField("mLoadedApk")
            mLoadedApkField.isAccessible = true
            val mLoadedApk: Any = mLoadedApkField.get(application)
            val mLoadedApkClass: Class<*> = mLoadedApk.javaClass
            val mActivityThreadField: Field = mLoadedApkClass.getDeclaredField("mActivityThread")
            mActivityThreadField.isAccessible = true
            val mActivityThread: Any = mActivityThreadField.get(mLoadedApk)
            val mActivityThreadClass: Class<*> = mActivityThread.javaClass
            val mActivitiesField: Field = mActivityThreadClass.getDeclaredField("mActivities")
            mActivitiesField.isAccessible = true
            val mActivities: Any = mActivitiesField.get(mActivityThread)
            // 注意这里一定写成Map，低版本这里用的是HashMap，高版本用的是ArrayMap
            if (mActivities is Map<*, *>) {
                val arrayMap = mActivities as Map<Any, Any>
                for ((_, value) in arrayMap) {
                    val activityClientRecordClass: Class<*> = value.javaClass
                    val activityField: Field =
                        activityClientRecordClass.getDeclaredField("activity")
                    activityField.isAccessible = true
                    val o: Any = activityField.get(value)
                    list!!.add(o as Activity)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            list = null
        }
        return list
    }
}
